package com.schoolMall.controller.product;

import com.schoolMall.domain.Product;
import com.schoolMall.domain.ProductCategory;
import com.schoolMall.domain.Shop;
import com.schoolMall.dto.ImageHolder;
import com.schoolMall.dto.ProductDto;
import com.schoolMall.enums.ProductStateEnum;
import com.schoolMall.service.ProductService;
import com.schoolMall.utils.CodeUtil;
import com.schoolMall.utils.HttpServletRequestUtil;
import com.schoolMall.utils.JsonUtil;
import com.schoolMall.utils.ModelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @author:zyh
 * @Time:2021-09-01-21:07
 * @email:1269231889@qq.com
 */
@Controller
@RequestMapping("/schoolMall/productManage")
public class ProductManagementController {
    @Autowired
    private ProductService productService;

    private static Logger logger = LoggerFactory.getLogger(ProductManagementController.class);

    private static final int IMAGE_MAX_COUNT = 6;

    @ResponseBody
    @PostMapping("/addProduct")
    public Map<String, Object> addProduct(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        if (!CollectionUtils.isEmpty(model = verifyCode(request))) {
            return model;
        }
        String productStr = HttpServletRequestUtil.getString(request, "productStr");
        try {
            Product product = JsonUtil.json2Object(productStr, Product.class);

            ImageHolder imageHolder = null;
            List<ImageHolder> productImgList = new ArrayList<>();
            imageHolder = getFileByRequest(request, productImgList);
            ProductDto productDto = productService.addProduct(product, imageHolder, productImgList);
            if (productDto.getProductStateEnum() == ProductStateEnum.SUCCESS) {
                model.put("success", true);
            } else {
                model.put("success", false);
            }
            model.put("msg", productDto);
        } catch (IOException e) {
            model.put("success", false);
            model.put("msg", e.toString());
        }
        return model;
    }

    @GetMapping("/getProductById")
    @ResponseBody
    public Map<String, Object> getProductById(@RequestParam long productId) {
        if (productId < 0) {
            return ModelUtil.fail("传入的productId为空");
        }
        Product product = null;
        try {
            product = productService.queryProductById(productId);
        } catch (Exception e) {
            return ModelUtil.fail("查询失败");
        }
        return ModelUtil.success(product);
    }

    @PostMapping("/modifyProduct")
    @ResponseBody
    public Map<String, Object> modifyProduct(HttpServletRequest request) {
        boolean statusChange = HttpServletRequestUtil.getBolean(request, "status");
        Map<String, Object> model = new HashMap<>();
        if (!statusChange && !CollectionUtils.isEmpty(model = verifyCode(request))) {
            return model;
        }
        String productStr = HttpServletRequestUtil.getString(request, "productStr");
        try {
            Product product = JsonUtil.json2Object(productStr, Product.class);
            ImageHolder imageHolder = null;
            List<ImageHolder> imageHolderList = new ArrayList<>();
            imageHolder = getFileByRequest(request, imageHolderList);
            ProductDto productDto = productService.modifyProduct(product, imageHolder, imageHolderList);
            if (productDto.getProductStateEnum() == ProductStateEnum.SUCCESS) {
                return ModelUtil.success(productDto);
            } else {
                return ModelUtil.fail("更新失败");
            }
        } catch (IOException e) {
            return ModelUtil.fail("json转换失败");
        }
    }

    @GetMapping("/getProListByShop")
    @ResponseBody
    public Map<String, Object> getProListByShop(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        int pageNum = HttpServletRequestUtil.getInt(request, "pageNum");
        int pageSize = HttpServletRequestUtil.getInt(request, "pageSize");
        Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
        if (pageNum > 0 & pageSize > 0 && Objects.nonNull(currentShop) && currentShop.getShopId() > 0) {
            long productCategoryId = HttpServletRequestUtil.getLong(request, "productCategoryId");
            String productName = HttpServletRequestUtil.getString(request, "productName");
            Product productCondition = compactProductCondition(currentShop.getShopId(), productCategoryId, productName);
            ProductDto productList = productService.getProductList(productCondition, pageNum, pageSize);
            model = ModelUtil.success(productList);
        } else {
            model = ModelUtil.fail("一部分信息为空");
        }
        return model;
    }

    private Product compactProductCondition(Long shopId, long productCategoryId, String productName) {
        Product product = new Product();
        Shop shop = new Shop();
        product.setShop(shop);
        shop.setShopId(shopId);
        if (productCategoryId > 0) {
            ProductCategory productCategory = new ProductCategory();
            productCategory.setProductCategoryId(productCategoryId);
            product.setProductCategory(productCategory);
        }

        if (!StringUtils.isEmpty(productName)) {
            product.setProductName(productName);
        }
        return product;
    }


    private Map<String, Object> verifyCode(HttpServletRequest request) {
        HashMap<String, Object> model = new HashMap<>();
        if (!CodeUtil.checkVerifyCode(request)) {
            logger.info("code error");
            model.put("success", false);
            model.put("msg", "验证码错误");
            return model;
        }
        return model;
    }

    private ImageHolder getFileByRequest(HttpServletRequest request, List<ImageHolder> imageHolderList) throws IOException {
        MultipartHttpServletRequest multipartHttpServletRequest = null;
        ImageHolder imageHolder = null;
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            CommonsMultipartFile thumbnail = (CommonsMultipartFile) multipartHttpServletRequest.getFile("thumbnail");
            imageHolder = new ImageHolder(thumbnail.getOriginalFilename(), thumbnail.getInputStream());
            for (int i = 0; i < IMAGE_MAX_COUNT; i++) {
                CommonsMultipartFile productImg = (CommonsMultipartFile)
                        multipartHttpServletRequest.getFile("productImg" + i);
                if (Objects.nonNull(productImg)) {
                    ImageHolder proImgHolder = new ImageHolder(productImg.getOriginalFilename(), productImg.getInputStream());
                    imageHolderList.add(proImgHolder);
                } else {
                    break;
                }
            }
        }
        return imageHolder;
    }
}
